package com.lic.demo;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.lic.demo.utils.ConvetUtil;

import java.io.File;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.entity.BAUDRATE;
import me.f1reking.serialportlib.entity.DATAB;
import me.f1reking.serialportlib.entity.FLOWCON;
import me.f1reking.serialportlib.entity.PARITY;
import me.f1reking.serialportlib.entity.STOPB;
import me.f1reking.serialportlib.listener.IOpenSerialPortListener;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;
import me.f1reking.serialportlib.listener.Status;

public class MainActivity extends AppCompatActivity{

    private static final String TAG = "MainActivity";
    SerialPortHelper mSerialPortHelper;
    EditText editText;
    Button open, close;
    TextView textView;

    byte[] bytes = new byte[]{10, 20, 30};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        //绑定控件视图
        open = findViewById(R.id.bt_open);
        close = findViewById(R.id.bt_close);
        textView = findViewById(R.id.tv_status);
        editText = findViewById(R.id.et_port);

        open.setOnClickListener(v -> initSerialPort());

        close.setOnClickListener(v -> close());
    }

    /**
     * 初始化串口信息
     */
    private void initSerialPort() {
        Log.i(TAG, "open: 打开串口");
        if (mSerialPortHelper == null) {
            mSerialPortHelper = new SerialPortHelper();
            mSerialPortHelper.setPort("/dev/" + editText.getText());
            mSerialPortHelper.setBaudRate(BAUDRATE.getBaudrate(BAUDRATE.B9600));
            mSerialPortHelper.setStopBits(STOPB.getStopBit(STOPB.B1));
            mSerialPortHelper.setDataBits(DATAB.getDataBit(DATAB.CS8));
            mSerialPortHelper.setParity(PARITY.getParity(PARITY.NONE));
            mSerialPortHelper.setFlowCon(FLOWCON.getFlowCon(FLOWCON.NONE));
        }
        Log.i(TAG, "open: " + Arrays.toString(mSerialPortHelper.getAllDeicesPath()));
        mSerialPortHelper.setIOpenSerialPortListener(new IOpenSerialPortListener() {
            @Override
            public void onSuccess(final File device) {
                Log.i(TAG, "run: 串口打开成功");

                runOnUiThread(() -> textView.setText("打开成功"));

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (mSerialPortHelper != null) {
                            Log.i(TAG, "run: 发送数据" + mSerialPortHelper.sendBytes(bytes));
                        }
                    }
                }, 2000, 10 * 1000);
            }

            @Override
            public void onFail(final File device, final Status status) {
                Log.i(TAG, "run: 打印失败结果" + status);
                switch (status) {
                    case NO_READ_WRITE_PERMISSION:
                        Log.i(TAG, "run: 没有读写权限");
                        break;
                    case OPEN_FAIL:
                    default:
                        Log.i(TAG, "onFail: 串口打开失败");
                        break;
                }
                runOnUiThread(() -> textView.setText("打开失败"));
            }
        });

        mSerialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
            @Override
            public void onDataReceived(final byte[] bytes) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "onDataReceived: " + Arrays.toString(bytes));
                        // TODO: 2021/6/22 接收到数据
                        String result = ConvetUtil.ConvetToHex(bytes);  //转换为16进制的字符串
                        handleCMD(result);  //根据反馈处理
                    }
                });
            }

            @Override
            public void onDataSend(byte[] bytes) {
                Log.i(TAG, "onDataSend: " + Arrays.toString(bytes));
            }
        });
        Log.i(TAG, "open: " + mSerialPortHelper.open());
    }

    /**
     * 处理接收到的串口数据
     *
     * @param cmd
     */
    private void handleCMD(String cmd) {
        Log.i(TAG, "handleCMD: 根据cmd处理命令" + cmd);
    }

    private void close() {
        if (mSerialPortHelper != null) {
            mSerialPortHelper.close();
        }
        textView.setText("已关闭");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        close();
    }
}